package com.dongdongshop.controller;

import com.dongdongshop.common.AjaxResult;
import com.dongdongshop.common.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillGoodsService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckill")
public class SeckillController {

    @DubboReference
    private SeckillGoodsService seckillGoodsService;
    /*跳转秒杀页*/
    @RequestMapping("toseckillIndex")
    public String toseckillIndex(Model model){
        /*查询缓存中的秒杀商品*/
        List<TbSeckillGoods> goodsList = seckillGoodsService.findSeckillList();
        model.addAttribute("goodsList",goodsList);
        return "seckill-index";
    }
    /*秒杀商品缓存预热,将秒杀商品提前加入缓存*/
    @RequestMapping("catchPreHot")
    @ResponseBody
    public String catchPreHot(){
        seckillGoodsService.catchPreHot();
        return "秒杀商品缓存预热完成!";
    }
    /*立即抢购,前往详情页面*/
    @RequestMapping("toSeckillItem")
    public String toSeckillItem(Long id,Model model){
        /*更具id查询商品信息*/
        TbSeckillGoods seckillGoods = seckillGoodsService.selectSeckillItemById(id);
        model.addAttribute("goods",seckillGoods);
        return "seckill-item";
    }
    /*立即抢购*/
    @RequestMapping("createOrder")
    @ResponseBody
    public AjaxResult createOrder(Long id){
        TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return  AjaxResult.R(ResultEnum.NO_LOGIN);
        }
        /*创建订单*/
        try {
            seckillGoodsService.createOrder(id,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.R(ResultEnum.GOODS_SOLD_OUT);
        }
        return AjaxResult.R(ResultEnum.SUCCESS);
    }


}
